<?php
/**
 * Desc:
 * User: hollowcg@foxmail.com
 * Date: 2019/5/25
 */

namespace app\admin\controller;


use app\common\model\UserRole;
use think\Db;
use think\Request;

class User extends Common
{
    /**
     * 用户页面
     * @return array|\think\response\View
     */
    public function user_index(){
        if (Request::instance()->isAjax()){
            $data = input();
            return \app\common\model\User::getDataArr($data);
        }
        return view();
    }

    /**
     * 用户保存
     * @return array
     */
    public function userSave(){
        $data = input();
        return \app\common\model\User::saveData($data,isset($data['id'])?$data['id']:'');
    }

    /**
     * 用户编辑页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user_edit(){
        $id = input('id');
        $data = Db::name('user')->find($id);
        $data['password'] = encry_code($data['password'],'DECODE');
        $this->assign('data',$data);
        return view();
    }

    /**
     * 删除用户
     */
    public function userDel(){
        $data = input();
        is_array($data['id']) ? $id = implode(',', $data['id']) : $id = $data['id'];
        $res = model('user')->destroy($id);
        if ($res !== false) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 角色页面
     * @return array|\think\response\View
     */
    public function role_index(){
        if (Request::instance()->isAjax()){
            $data = input();
            return \app\common\model\UserRole::getDataArr($data);
        }
        return view();
    }

    public function role_edit(){
        $id = input('id');
        $data = Db::name('userRole')->find($id);
        $this->assign('data',$data);

        return view();
    }
    /**
     * 获取权限菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMenu(){
        $RoleId = input('role_id');
        $data = \app\common\model\Menu::getDataAdminMenu('list',$RoleId);
        return ['code'=>0,'data'=>$data];
    }

    /**
     * 用户角色保存
     * @return array
     */
    public function userRoleSave(){
        $data = input();
        if (isset($data['menu_id'])){
            $data['menu_id'] = implode(',',$data['menu_id']);
        }

        return UserRole::saveData($data,isset($data['id'])?$data['id']:'');
    }

    public function roleDel(){
        $data = input();
        is_array($data['id']) ? $id = implode(',', $data['id']) : $id = $data['id'];
        $res = model('userRole')->destroy($id);
        if ($res !== false) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}